from django.shortcuts import render, redirect
from .forms import UploadImageForm, ImageUploadForm
from django.core.files.storage import FileSystemStorage
from django.conf import settings
from .opencv_dface import opencv_dface


# Create your views here.
def first_view(request):

    render(request, 'opencv_webapp/first_view.html', {})


def uimage(request):

    if request.method == "POST":
        form = UploadImageForm(request.POST, request.FILES)

        if form.is_valid():
            myfile = request.FILES['image']
            fs = FileSystemStorage()
            filename = fs.save(myfile.name, myfile)

            uploaded_file_url = fs.url(filename)

            context = {'form': form,
                    'uploaded_file_url': uploaded_file_url,
                    }
        return render(request, 'opencv_webapp/uimage.html', context)

    else:
        form = UploadImageForm()

        return render(request, 'opencv_webapp/uimage.html', {'form': form})


def dface(request):

    if request.method == 'POST':
        form = ImageUploadForm(request.POST, request.FILES)
        if form.is_valid():
            post = form.save(commit=False)
            post.save()

            imageURL = settings.MEDIA_URL + form.instance.document.name
            opencv_dface(settings.MEDIA_ROOT_URL + imageURL)
            context = {
                'form': form,
                'post': post,
            }
        return render(request, 'opencv_webapp/dface.html', context)

    else:
        form = ImageUploadForm()
        context = {
            'form': form,
        }
        return render(request, 'opencv_webapp/dface.html', context)
